package epic.services.implementation;

import epic.domain.Hero;
import epic.domain.PathDecision;
import epic.services.HeroService;
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * JPA {@link HeroService} implementation.
 * 
 * @author Artem Kozlov
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class HeroServiceImpl implements HeroService {

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * Create new {@code Hero} with given named.
     * 
     * @param heroName new hero name
     * @return new Hero.
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public Hero createNewHero(String heroName) {
        Hero hero = new Hero(heroName);
        hero.setDecision(PathDecision.UNDEFINED);
        entityManager.persist(hero);
        return hero;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public Hero setHeroPathDescision(Hero hero, PathDecision decision) {
        hero.setDecision(decision);
        entityManager.merge(hero);
        return hero;
    }

    /**
     * Get all existing heroes.
     * 
     * @return 
     */
    @Override
    public Collection<Hero> getAllHeros() {
        return entityManager.createNamedQuery(Hero.GET_ALL_HEROS).getResultList();
    }
}
